package com.tim.app.server.net;

import android.text.TextUtils;

import com.application.library.log.DLOG;
import com.lzy.okhttputils.model.HttpParams;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.server.logic.UserManager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求参数排序加Key然后md5拼接参数
 *
 * @author
 */
public class SignRequestParams {

    private SignRequestParams() {

    }

    private static SignRequestParams api = null;

    public static SignRequestParams ins() {
        if (api == null) {
            api = new SignRequestParams();
        }
        return api;
    }

    public void init() {

    }

    public static String MDString(String str) {
        MessageDigest md5 = null;
        byte[] byteArray = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        try {
            byteArray = str.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            hexValue.append(String.format("%02x", (md5Bytes[i]) & 0xff));
        }
        return hexValue.toString().toLowerCase();
    }

    public static String sign_encode(Map<String, Object> mp) {
        String result = "";
        List<String> ns = new ArrayList<String>();
        ns.clear();
        for (Map.Entry<String, Object> entry : mp.entrySet()) {
            if (entry.getValue() != null && !TextUtils.isEmpty(entry.getValue().toString().trim())) {
                ns.add(entry.getKey());
            }
        }
        Collections.sort(ns);
        for (String s : ns) {
            try {
                result += s + "=" + URLEncoder.encode(mp.get(s).toString(), "UTF-8") + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        result += "key=" + UserManager.ins().getToken();
        return result;
    }

    public static String getSign(Map<String, Object> map) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && !TextUtils.isEmpty(entry.getValue().toString().trim())) {
//                    list.add(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8") + "&");

                list.add(entry.getKey());

            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
//            sb.append(arrayToSort[i]);
            sb.append(map.get(arrayToSort[i]));
        }
        String result = sb.toString();
        return result;
    }

    public static HttpParams generationParams(HashMap<String, Object> params, boolean isSign) {
        if (isSign) {
            try {
                String token = UserManager.ins().getToken();
                String signValue = getSign(params);
                String base64Value = encodeBASE64(signValue.getBytes());
                String sign_e = MDString(base64Value) + token;
                String sign = MDString(sign_e);
                params.put(NetWorkRequestParams.SIGN, sign);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<String> keys = new ArrayList<String>();
        keys.clear();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            keys.add(entry.getKey());
        }
//        Collections.sort(keys);
        HttpParams realParams = new HttpParams();
        String paramsStr = "";
        for (String key : keys) {
            try {
//                realParams.put(key, URLEncoder.e  ncode(String.valueOf(params.get(key)), "UTF-8"));
                realParams.put(key, String.valueOf(params.get(key)));
                if (RT.DEBUG) {
                    paramsStr = paramsStr + key + "=" + URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8") + "&";
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        if (RT.DEBUG && paramsStr.length() > 0) {
            paramsStr = paramsStr.substring(0, paramsStr.length() - 1);
            DLOG.d(AppKey.HTTP_TAG, paramsStr);
        }
        return realParams;
    }

    private static char[] codec_table = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
            'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
            'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', '+', '/'};


    public static String encodeBASE64(byte[] a) {
        int totalBits = a.length * 8;
        int nn = totalBits % 6;
        int curPos = 0;// process bits
        StringBuffer toReturn = new StringBuffer();
        while (curPos < totalBits) {
            int bytePos = curPos / 8;
            switch (curPos % 8) {
                case 0:
                    toReturn.append(codec_table[(a[bytePos] & 0xfc) >> 2]);
                    break;
                case 2:

                    toReturn.append(codec_table[(a[bytePos] & 0x3f)]);
                    break;
                case 4:
                    if (bytePos == a.length - 1) {
                        toReturn
                                .append(codec_table[((a[bytePos] & 0x0f) << 2) & 0x3f]);
                    } else {
                        int pos = (((a[bytePos] & 0x0f) << 2) | ((a[bytePos + 1] & 0xc0) >> 6)) & 0x3f;
                        toReturn.append(codec_table[pos]);
                    }
                    break;
                case 6:
                    if (bytePos == a.length - 1) {
                        toReturn
                                .append(codec_table[((a[bytePos] & 0x03) << 4) & 0x3f]);
                    } else {
                        int pos = (((a[bytePos] & 0x03) << 4) | ((a[bytePos + 1] & 0xf0) >> 4)) & 0x3f;
                        toReturn.append(codec_table[pos]);
                    }
                    break;
                default:
                    //never hanppen
                    break;
            }
            curPos += 6;
        }
        if (nn == 2) {
            toReturn.append("==");
        } else if (nn == 4) {
            toReturn.append("=");
        }
        return toReturn.toString();

    }

}
